package com.czxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.dao.SysPermissionMapper;
import com.czxy.rbac.SysPermission;
import com.czxy.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {
    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public List<SysPermission> findAll() {
        //1 查找所有的一级菜单
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",0);
        List<SysPermission> onePermissionList = baseMapper.selectList(queryWrapper);
        //2 遍历一级菜单，查找出二级菜单
        for (SysPermission onePermission:onePermissionList){
            QueryWrapper<SysPermission> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("parent_id",onePermission.getId());
            List<SysPermission> towPermissionList = baseMapper.selectList(queryWrapper2);
            HashSet<SysPermission> set = new HashSet<>();
            set.addAll(towPermissionList);
            onePermission.setChildren(set);
        }
        return onePermissionList;
    }

    @Override
    public Set<SysPermission> findPermByUserIdAndParentId(Integer userId) {
        //先查找一级菜单，遍历一级菜单查找二级菜单
        Set<SysPermission> onePermSet = permissionMapper.findByUserIdAndParentId(userId, 0);
        //遍历一级菜单查找二级菜单
        for (SysPermission onePerm:onePermSet){
            Set<SysPermission> towPermSet = permissionMapper.findByUserIdAndParentId(userId, onePerm.getId());
            onePerm.setChildren(towPermSet);
        }
        return onePermSet;
    }
}
